"use client"
import { Card } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { useState, useEffect } from 'react';
import { PlusCircle, Loader2, X, Mail, Clock, AlertCircle, UserMinus, LogOut } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { toast } from "sonner";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { useTranslations } from 'next-intl';
import { getUserTeam, TeamMemberType, createTeamMember, getTeamMembers, updateTeamMember, deleteTeamMember } from '@/controller/team_members';
import { createNewTeam, getTeamData, TeamDataType, deleteTeam } from '@/controller/team';
import { getUser, getUserProfile } from '@/controller/auth';
import { User } from '@supabase/supabase-js'
import { getProjectsByTeamId } from '@/controller/project'

export default function TeamsPage() {
  const t = useTranslations('team');
  const [teamMembers, setTeamMembers] = useState<TeamMemberType[] | null>(null);
  const [currentUserRole, setCurrentUserRole] = useState<string | null>(null);
  const [email, setEmail] = useState('');
  const [inviteLoading, setInviteLoading] = useState(false);
  const [role, setRole] = useState('Member');
  const [isInTeam, setIsInTeam] = useState(true);
  const [userInfo, setUserInfo] = useState<User>();
  const [teamData, setTeamData] = useState<TeamDataType | null>(null);
  const [currentUserInvitation, setCurrentUserInvitation] = useState<TeamMemberType | null>(null);
  const [confirmDialogOpen, setConfirmDialogOpen] = useState(false);
  const [memberToRemove, setMemberToRemove] = useState<TeamMemberType | null>(null);
  const [isExit, setIsExit] = useState(false);
  const [removeMemberLoading, setRemoveMemberLoading] = useState<string | null>(null);
  const init = async () => {
    const user = await getUser();
    if (!user) {
      toast.error('user not found');
      return;
    }
    setUserInfo(user);
    const { data, error } = await getUserTeam(user.id);
    if (!error && data) {
      // 在团队内
      console.log('在团队内', data);
      const { data: teamData, error: teamDataError } = await getTeamData(data.team_id);
      if (!teamData || teamDataError) {
        toast.error('get team data failed');
        return;
      }
      setTeamData(teamData);
      setCurrentUserRole(data.role);
      if (data.status === 'active') {
        const { data: teamMembers, error: teamMembersError } = await getTeamMembers(data.team_id);
        if (!teamMembers || teamMembersError) {
          toast.error('get team members failed');
          return;
        }
        setTeamMembers(teamMembers);
        setCurrentUserInvitation(null)
      } else {
        setTeamMembers([])
        setCurrentUserInvitation(data)
      }
    } else {
      // 不在团队内
      setTeamMembers([])
      setCurrentUserRole('Owner');
      setIsInTeam(false);
      setCurrentUserInvitation(null)
      console.log(error?.message);
    }
  }
  const handleInvite = async () => {
    if (!email.trim()) return;
    setInviteLoading(true);
    try {
      const { data: inviteUser, error: inviteUserError } = await getUserProfile({ key: 'email', val: email });
      if (inviteUserError) {
        toast.error('invite user not found');
        return;
      }
      if (isInTeam) {
        if (!teamData || !userInfo) {
          toast.error('team data or user info not found');
          return;
        }
        // 在团队内
        const { error: inviteteamMemberError } = await createTeamMember({
          team_id: teamData.team_id,
          user_id: inviteUser.id,
          role,
          email: inviteUser.email!,
          status: 'invited',
          invited_by: userInfo.id,
          inviter: userInfo.email!
        });
        if (inviteteamMemberError) {
          toast.error(t('inviteFailed'), {
            description: inviteteamMemberError.message || t('inviteFailedDescription')
          });
          init();
          return;
        }
      } else {
        if (!userInfo) {
          toast.error('current user not found');
          return;
        }
        // 不在团队内
        const { data: team, error: teamError } = await createNewTeam(userInfo.id, userInfo.email!);
        if (!team || teamError) {
          toast.error('create team failed');
          return;
        }
        const { error: teamMemberError } = await createTeamMember({
          team_id: team.team_id,
          user_id: userInfo.id,
          role: 'Owner',
          email: userInfo.email!,
          status: 'active'
        });
        if (teamMemberError) {
          toast.error('create team member failed');
          return;
        }
        const { error: inviteteamMemberError } = await createTeamMember({
          team_id: team.team_id,
          user_id: inviteUser.id,
          role,
          email: inviteUser.email!,
          status: 'invited',
          invited_by: userInfo.id,
          inviter: userInfo.email!
        });
        if (inviteteamMemberError) {
          toast.error(t('inviteFailed'), {
            description: inviteteamMemberError.message || t('inviteFailedDescription')
          });
          init();
          return;
        }
      }
      init();
      setEmail('');
      toast.success(t('inviteSent'), {
        description: t('inviteSentDescription', { email })
      });
    } catch (error: unknown) {
      // const errorMsg = error instanceof Error ? error.message : String(error);
      // toast.error(t('inviteFailed'), {
      //   description: errorMsg || t('inviteFailedDescription')
      // });
    } finally {
      setInviteLoading(false);
    }
  };

  // 打开移除成员确认对话框
  const openRemoveConfirmDialog = (member: TeamMemberType) => {
    setMemberToRemove(member);
    setConfirmDialogOpen(true);
    setIsExit(false);
  };

  const openExitConfirmDialog = (member: TeamMemberType) => {
    setMemberToRemove(member);
    setConfirmDialogOpen(true);
    setIsExit(true);
  };

  const handleAcceptInvite = async () => {
    // TODO: 处理接受邀请
    if (!userInfo) {
      toast.error(t('acceptFailed'), {
        description: 'user not found'
      });
      return;
    }
    const { data, error } = await updateTeamMember({ status: 'active', user_id: userInfo.id });
    if (!data || error) {
      toast.error(t('acceptFailed'), {
        description: error?.message || t('acceptFailedDescription')
      });
      return;
    }
    toast.success(t('acceptInvitation'), {
      description: t('joinTeamSuccess')
    });
    init();
  };

  const handleRejectInvite = async () => {
    // TODO: 处理拒绝邀请
    if (!userInfo) {
      toast.error(t('rejectFailed'), {
        description: 'user not found'
      });
      return;
    }
    const { data, error } = await deleteTeamMember(userInfo.id);
    if (!data || error) {
      toast.error(t('rejectFailed'), {
        description: error?.message || t('rejectFailedDescription')
      });
      return;
    }
    toast.success(t('rejectInvitation'), {
      description: t('rejectInviteSuccess')
    });
    init();
  };

  const handleRemoveMember = async (memberId: string) => {
    if (!teamData || !userInfo) {
      toast.error(t('removeFailed'), {
        description: 'team or user not found'
      });
      return;
    }
    if (userInfo.id === teamData.owner_id) {
      const { data, error } = await getProjectsByTeamId(teamData.team_id)
      if (!data || error) {
        toast.error(t('removeFailed'), {
          description: error?.message || t('removeMemberFailed')
        });
        return;
      }
      if (data.length > 0) {
        toast.error(t('removeFailed'), {
          description: 'team has projects, cannot remove'
        });
        return;
      }
    }
    setRemoveMemberLoading(memberId);
    const { data, error } = await deleteTeamMember(memberId);
    if (!data || error) {
      toast.error(t('removeFailed'), {
        description: error?.message || t('removeMemberFailed')
      });
      setRemoveMemberLoading(null);
      return;
    }
    if (isExit) {
      toast.success(t('exitSuccess'), {
        description: t('exitSuccessDescription')
      });
    } else {
      toast.success(t('removeMemberSuccess'), {
        description: t('removeMemberSuccessDescription')
      });
    }
    if (userInfo.id === teamData.owner_id) {
      const { data, error } = await deleteTeam(teamData.team_id, userInfo.id);
      if (!data || error) {
        toast.error(t('removeFailed'), {
          description: error?.message || t('removeMemberFailed')
        });
        return;
      }
    }
    setRemoveMemberLoading(null);
    setConfirmDialogOpen(false);
    init();
  };

  useEffect(() => {
    init();
  }, []);
  return (
    <div className="min-h-screen flex flex-col">
      <main className="flex-1 container mx-auto py-6 space-y-6 h-full">
        <div className="space-y-6">
          {/* 显示被邀请用户的视图 */}
          {currentUserInvitation && (
            <Card className="p-6 border-blue-200 bg-blue-50">
              <div className="flex items-center mb-6">
                <Mail className="w-6 h-6 text-blue-600 mr-3" />
                <h2 className="text-xl font-semibold text-blue-700">{t('youHaveInvitation')}</h2>
              </div>

              <div className="bg-white p-6 rounded-lg border border-blue-200 mb-6">
                <div className="mb-4">
                  <h3 className="font-medium text-gray-700">{t('invitationDetails')}</h3>
                  <div className="mt-2 space-y-2">
                    <div className="flex items-center">
                      <span className="text-gray-500 w-45">{t('teamName')}:</span>
                      <span className="font-medium">{teamData?.name}</span>
                    </div>
                    <div className="flex items-center">
                      <span className="text-gray-500 w-45">{t('inviter')}:</span>
                      <span className="font-medium">{currentUserInvitation.inviter}</span>
                    </div>
                    <div className="flex items-center">
                      <span className="text-gray-500 w-45">{t('invitationTime')}:</span>
                      <span className="font-medium">
                        {currentUserInvitation.invited_at ?
                          new Date(currentUserInvitation.invited_at).toLocaleString('zh-CN',
                            { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
                          : t('unknown')}
                      </span>
                    </div>
                    <div className="flex items-center">
                      <span className="text-gray-500 w-45">{t('role')}:</span>
                      <Badge variant="outline" className="font-medium">{currentUserInvitation.role}</Badge>
                    </div>
                  </div>
                </div>

                <div className="flex space-x-4">
                  <Button
                    onClick={() => handleAcceptInvite()}
                    className="bg-blue-600 hover:bg-blue-700 text-white"
                  >
                    {t('acceptInvitation')}
                  </Button>
                  <Button
                    variant="outline"
                    onClick={() => handleRejectInvite()}
                    className="border-red-300 text-red-600 hover:bg-red-50"
                  >
                    {t('rejectInvitation')}
                  </Button>
                </div>
              </div>

              <div className="text-sm text-gray-500">
                <p>{t('invitationNote')}</p>
              </div>
            </Card>
          )}
          {/* 团队成员列表 */}
          <Card className="p-6">
            <div className="flex justify-between items-center mb-4">
              <h2 className="text-xl font-semibold">{t('teamMembers')}</h2>
            </div>
            <div className="space-y-4">
              {
                teamMembers ? (
                  teamMembers.length > 0 ? (
                    teamMembers.map((member) => (
                      <div key={member.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                        <div className="flex items-center">
                          <div className="flex items-center justify-center w-8 h-8 bg-gray-200 rounded-full mr-3">
                            {member.email
                              ? member.email[0].toUpperCase()
                              : '?'}
                          </div>
                          <div>
                            <div className="font-medium">{member.email}</div>
                            <div className="text-sm text-gray-500">
                              {teamData && teamData.owner_id === member.user_id ? t('owner') : member.role}
                              <Badge variant="secondary"
                                className="bg-blue-500 text-white dark:bg-blue-600 ml-2">{member.status}</Badge>
                            </div>
                          </div>
                        </div>
                        <div className="flex items-center">

                          {/* 不能移除自己 */}
                          {currentUserRole === 'Owner' && userInfo?.id !== member.user_id && (
                            <Button
                              variant="ghost"
                              size="sm"
                              className="text-gray-500 hover:text-red-500"
                              onClick={() => openRemoveConfirmDialog(member)}
                            >
                              <UserMinus className="w-4 h-4" />
                            </Button>
                          )}
                          {userInfo?.id === member.user_id && (
                            <Button
                              variant="ghost"
                              size="sm"
                              className="text-gray-500 hover:text-red-500"
                              onClick={() => openExitConfirmDialog(member)}
                            >
                              <LogOut className="w-4 h-4 text-red-600" />
                            </Button>
                          )}
                        </div>
                      </div>
                    ))
                  ) : (
                    <div className="text-center py-4 text-gray-500">{t('noTeamMembers')}</div>
                  )
                ) : (
                  <div className="flex flex-col items-center justify-center text-gray-500">
                    <Loader2 className="w-8 h-8 mb-2 animate-spin" />
                    <p>{t('loadingTeamInfo')}</p>
                  </div>
                )
              }
            </div>
          </Card>
          {/* 邀请新成员表单 - 仅对所有者和管理员显示 */}
          {currentUserRole === 'Owner' && (
            <Card className="p-6">
              <h2 className="text-xl font-semibold mb-4">{t('inviteTeamMember')}</h2>

              <div className="space-y-4">
                <div>
                  <label htmlFor="email" className="block mb-2">{t('email')}</label>
                  <Input
                    id="email"
                    placeholder={t('emailPlaceholder')}
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                  />
                </div>

                <div>
                  <label className="block mb-2">{t('role')}</label>
                  <RadioGroup value={role} onValueChange={setRole} className="flex gap-4">
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="Member" id="Member" />
                      <label htmlFor="Member">{t('member')}</label>
                    </div>
                    <div className="flex items-center space-x-2">
                      <RadioGroupItem value="Owner" id="Owner" />
                      <label htmlFor="Owner">{t('owner')}</label>
                    </div>
                  </RadioGroup>
                </div>

                <Button
                  onClick={handleInvite}
                  disabled={!email.trim() || inviteLoading}
                >
                  {inviteLoading ? (
                    <>
                      <Loader2 className="w-4 h-4 mr-1 animate-spin" />
                      {t('processing')}
                    </>
                  ) : (
                    <>
                      <PlusCircle className="w-4 h-4 mr-1" />
                      {t('inviteMember')}
                    </>
                  )}
                </Button>
              </div>
            </Card>
          )}
        </div>
      </main>
      {/* 移除成员确认对话框 */}
      <Dialog open={confirmDialogOpen} onOpenChange={setConfirmDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{isExit ? t('confirmExitTeam') : t('confirmRemoveMember')}</DialogTitle>
            <DialogDescription>
              {isExit ? t('confirmExitDescription') : t('confirmRemoveDescription', { email: memberToRemove?.email || t('thisMember') })}
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setConfirmDialogOpen(false)}>{t('cancel')}</Button>
            <Button
              variant="destructive"
              onClick={() => memberToRemove && handleRemoveMember(memberToRemove.user_id)}
              disabled={removeMemberLoading !== null}
            >
              {removeMemberLoading ? (
                <>
                  <Loader2 className="w-4 h-4 mr-1 animate-spin" />
                  {t('processing')}
                </>
              ) : (isExit ? t('exitTeam') : t('remove'))}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
